<template>
  <view>
    <cu-custom bgColor="bg-gradual-green" :isBack="true">
      <block slot="backText">返回</block>
      <block slot="right">
        <view class="u-m-r-40" @tap="exportData">导出记录</view>
      </block>
    </cu-custom>

    <view class="wrap">
      <!-- 查询系列 -->
      <view class="u-demo-area u-flex u-row-center u-m-p-50">
        <u-dropdown
          :close-on-click-mask="mask"
          ref="uDropdown"
          :activeColor="activeColor"
          :borderBottom="false"
          @close="closeChange"
        >
          <u-dropdown-item @change="change" title="账本" v-model="bookId" :options="books"></u-dropdown-item>
          <u-dropdown-item
            @change="categoryChange"
            title="类别"
            v-model="categoryId"
            :options="categorys"
          ></u-dropdown-item>
          <u-dropdown-item title="类型">
            <view class="slot-content" style="background-color: #ffffff">
              <view class="u-flex u-row-center">
                <button class="type-y-btn" @click="selectTypesAll">全部选中</button>
                <button class="type-n-btn" @click="cancelTypesAll">取消全选</button>
              </view>
              <view class="item-box">
                <view
                  class="item"
                  :class="[item.active ? 'active' : '']"
                  @tap="tagClick(index)"
                  v-for="(item, index) in types"
                  :key="index"
                >
                  {{ item.label }}
                </view>
              </view>
            </view>
          </u-dropdown-item>
        </u-dropdown>
      </view>

      <view>
        <view class="u-flex u-flex-nowrap picker-border">
          <view
            @tap="calendarShow = true"
            class="u-m-l-40 u-font-30"
            style="margin-right: auto; justify-content: flex-start"
          >
            {{ startInput ? startInput : startNowTime }}
          </view>
          <view style="justify-content: center">-</view>
          <view
            @tap="calendarShow = true"
            class="u-m-r-40 u-font-30"
            style="margin-left: auto; justify-content: flex-end"
          >
            {{ endInput ? endInput : endNowTime }}
          </view>
        </view>

        <!-- 日历选择 -->
        <u-calendar
          v-model="calendarShow"
          mode="range"
          @change="calendarChange"
          active-bg-color="#19be6b"
          range-color="#19be6b"
          range-bg-color="rgba(25,190,107, 0.13)"
          btn-type="success"
          :default-start-date="startNowDate"
          :default-end-date="endNowDate"
        ></u-calendar>
      </view>

      <!-- 汇总金额展示 -->
      <view class="top u-flex u-flex-nowrap">
        <view class="color-blue">总金额: {{ amtSummary ? amtSummary : '0.00' }}</view>
        <view class="color-green">总收入: + {{ incomeAmtSummary ? incomeAmtSummary : '0.00' }}</view>
        <view class="color-red">总支出: - {{ expenditureAmtSummary ? expenditureAmtSummary : '0.00' }}</view>
      </view>

      <!-- 饼状图 -->
      <u-collapse :head-style="itemStyle">
        <u-collapse-item
          ref="collapseHeight"
          :title="categoryId == 1 ? '支出饼状图' : '收入饼状图'"
          :open="open"
          @change="itemChange"
        >
          <view class="chartsMain">
            <canvas canvas-id="canvasPie" id="canvasPie" class="charts" @touchstart="touchPie"></canvas>
          </view>
        </u-collapse-item>
      </u-collapse>
      <!-- <view class="cu-bar bg-white margin-top-xs">
				<view class="action sub-title">
					<text class="text-xl text-bold text-blue text-shadow">{{ categoryId == 1 ? '支出' : '收入' }}饼状图</text>
					<text class="text-ABC text-blue">PieCharts</text>
				</view>
			</view>
			<view class="chartsMain">
				<canvas canvas-id="canvasPie" id="canvasPie" class="charts" @touchstart="touchPie"></canvas>
			</view> -->

      <!-- 查询列表 -->
      <scroll-view scroll-y class="sv" :style="{ height: navHeight + 'px' }">
        <view class="page-box">
          <!-- <view class="order" v-for="(item, index) in Pie.series" :key="item.id">
						<view class="order-item">
							<view class="left u-text-left">
								<view class="title">{{ item.name }}</view>
							</view>
							<view class="right u-text-right">
								<view class="expenditure-type" v-if="categoryId == 1">- {{ item.data }}</view>
								<view class="income-type" v-else>+ {{ item.data }}</view>
							</view>
						</view>
					</view> -->

          <u-swipe-action v-for="(item, index) in Pie.series" :key="item.id" :index="index" :options="options" @click="click">
            <view class="order u-border-bottom">
              <view class="order-item">
                <view class="left u-text-left">
                  <view class="title">{{ item.name }}</view>
                </view>
                <view class="right u-text-right">
                  <view class="expenditure-type" v-if="categoryId == 1">- {{ item.data }}</view>
                  <view class="income-type" v-else>+ {{ item.data }}</view>
                </view>
              </view>
            </view>
          </u-swipe-action>
        </view>
      </scroll-view>
    </view>

    <!-- 确认导出框 -->
    <Confirm ref="Confirm"></Confirm>
  </view>
</template>

<script>
import Confirm from '@/components/confirm.vue'
// 图表
import uCharts from '@/components/u-charts/u-charts.js'
var _self
var canvaPie = null

export default {
  data() {
    return {
      incomeAmtSummary: null,
      expenditureAmtSummary: null,
      amtSummary: null,
      pH: 0, //窗口高度
      navHeight: 0, //元素的所需高度
      activeColor: '#19be6b',
      mask: true,
      books: [],
      categorys: [
        {
          label: '支出',
          value: 1
        },
        {
          label: '收入',
          value: 2
        }
      ],
      types: [],
      bookId: 1,
      categoryId: 1,
      startNowTime: '',
      endNowTime: '',
      startNowDate: '',
      endNowDate: '',
      startInput: '',
      endInput: '',
      cWidth: '',
      cHeight: '',
      pixelRatio: 1,
      // 饼状图
      Pie: {
        series: []
      },
      // 折叠栏
      open: true,
      itemStyle: {
        marginLeft: '40rpx',
        marginRight: '20rpx'
      },
      collapseHeight: 580,
      calendarShow: false,
      options: [
        {
          text: '详情',
          style: {
            backgroundColor: '#007aff'
          }
        }
      ]
    }
  },
  onReady() {
    // 动态获取剩余的高度
    var that = this
    uni.getSystemInfo({
      success: function (res) {
        that._data.pH = res.windowHeight //windoHeight为窗口高度，主要使用的是这个
        let titleH = uni.createSelectorQuery().select('.sv') //想要获取高度的元素名（class/id
        titleH
          .boundingClientRect((data) => {
            let pH = that._data.pH
            let collapseHeightPx = that.$u.utils.rpxTopx(that._data.collapseHeight)
            that._data.navHeight = pH - data.top - collapseHeightPx //计算高度：元素高度=窗口高度-元素距离顶部的距离（data.top）
          })
          .exec()
      }
    })
  },
  onUnload() {
    // 移除刷新监听
    uni.$off('refreshChartsPage')
  },
  onLoad() {
    // 刷新监听
    uni.$on('refreshChartsPage', () => {
      // 执行刷新方法
      this.change()
    })

    _self = this
    this.cWidth = uni.upx2px(750)
    this.cHeight = uni.upx2px(520)
    this.getNowTime()
    this.getAccountBookList()
    this.getTypeListByCategoryId(this.categoryId)
  },
  components: {
    Confirm
  },
  methods: {
    getServerData() {
      _self.showPie('canvasPie', this.Pie)
    },
    showPie(canvasId, chartData) {
      canvaPie = new uCharts({
        $this: _self,
        canvasId: canvasId,
        type: 'pie',
        fontSize: 11,
        legend: true,
        background: '#FFFFFF',
        pixelRatio: _self.pixelRatio,
        series: _self.Pie.series,
        animation: true,
        width: _self.cWidth * _self.pixelRatio,
        height: _self.cHeight * _self.pixelRatio,
        dataLabel: true,
        extra: {
          pie: {
            lableWidth: 15
          }
        }
      })
    },
    touchPie(e) {
      canvaPie.showToolTip(e, {
        format: function (item) {
          return item.name + ':' + item.data
        }
      })
    },
    /**
     * 获取汇总金额数据
     */
    async getAmtSummary() {
      let startInput = this.startInput ? this.startInput : this.startNowTime
      let endInput = this.endInput ? this.endInput : this.endNowTime
      let accountCategoryIds = []
      this.types.forEach((type) => {
        if (!type.active) return
        accountCategoryIds.push(type.value)
      })

      // 获取数据
      const params = {
        accountBookId: this.bookId,
        accountCategoryIds: accountCategoryIds,
        startTime: startInput,
        endTime: endInput
      }
      const res = await this.$u.api.getAmtSummary(params)
      this.incomeAmtSummary = res.incomeAmtSummary
      this.expenditureAmtSummary = res.expenditureAmtSummary
      this.amtSummary = res.amtSummary
    },
    /**
     * 获取所有的账本信息
     */
    async getAccountBookList() {
      const res = await this.$u.api.getAccountBookList()
      let data = JSON.parse(JSON.stringify(res))

      this.books = []
      data.forEach((item) => {
        let dat = {
          label: item.name,
          value: item.id
        }

        this.books.push(dat)
      })
    },
    /**
     * 获取图表数据
     */
    async getCount() {
      let startInput = this.startInput ? this.startInput : this.startNowTime
      let endInput = this.endInput ? this.endInput : this.endNowTime
      let accountCategoryIds = []
      this.types.forEach((type) => {
        if (!type.active) return
        accountCategoryIds.push(type.value)
      })

      let params = {
        accountBookId: this.bookId,
        accountCategoryIds: accountCategoryIds,
        startTime: startInput,
        endTime: endInput
      }
      let res

      if (this.categoryId == 1) {
        // 获取支出
        res = await this.$u.api.getExpenditureCount(params)
      } else {
        // 获取收入
        res = await this.$u.api.getIncomeCount(params)
      }
      let data = JSON.parse(JSON.stringify(res))

      if (data) {
        this.Pie.series = []

        // 组装数据
        data.forEach((item) => {
          let dat = {
            name: item.name,
            data: item.amt,
            id: item.categoryId
          }

          this.Pie.series.push(dat)
        })

        // 图表显示
        this.getServerData()
      }
    },
    async change() {
      // 列表重新查询
      this.dataList = []
      this.current = 1
      this.getAmtSummary()
      this.getCount()
    },
    async categoryChange() {
      this.getTypeListByCategoryId(this.categoryId)
    },
    closeDropdown() {
      this.$refs.uDropdown.close()
    },
    async closeChange(index) {
      if (index !== 2) return
      // 类型关闭刷新
      this.dataList = []
      this.current = 1
      this.getAmtSummary()
      this.getCount()
    },
    /**
     * 日历改变事件
     * @param {Object} e
     */
    calendarChange(e) {
      this.startNowDate = e.startDate
      this.endNowDate = e.endDate
      this.startInput = e.startDate + ' 00:00:00'
      this.endInput = e.endDate + ' 23:59:59'

      this.change()
    },
    /**
     * 获取当前 年月日
     */
    async getNowTime() {
      var dt = new Date()
      let year = dt.getFullYear()
      let month = (dt.getMonth() + 1).toString().padStart(2, '0')
      let date = dt.getDate().toString().padStart(2, '0')
      this.startNowTime = `${year}-${month}-01 00:00:00`
      this.endNowTime = `${year}-${month}-${date} 23:59:59`
      this.startNowDate = `${year}-${month}-01`
      this.endNowDate = `${year}-${month}-${date}`
    },
    /**
     * 根据类别查询类型信息
     * @param {Object} categoryId
     */
    async getTypeListByCategoryId(categoryId) {
      const res = await this.$u.api.getTypesByCategory(categoryId)
      let data = JSON.parse(JSON.stringify(res))

      this.types = []
      data.forEach((item) => {
        let dat = {
          label: item.typeName,
          value: item.id,
          active: true
        }

        this.types.push(dat)
      })

      this.dataList = []
      this.current = 1
      this.getAmtSummary()
      this.getCount()
    },
    tagClick(index) {
      this.types[index].active = !this.types[index].active
    },
    /**
     * 跳转详情页面
     * @param {Object} index1
     * @param {Object} index
     */
    click(index, index1) {
      let id = this.Pie.series[index].id
      let startInput = this.startInput ? this.startInput : this.startNowTime
      let endInput = this.endInput ? this.endInput : this.endNowTime

      this.$u.route({
        type: 'navigateTo',
        url: `/pages/index/account/account_category?id=${id}&bookId=${this.bookId}&startInput=${startInput}&endInput=${endInput}`
      })
    },
    selectTypesAll() {
      this.types.forEach((type) => {
        type.active = true
      })
    },
    cancelTypesAll() {
      this.types.forEach((type) => {
        type.active = false
      })
    },
    /**
     * 导出账单明细记录
     */
    exportData() {
      let startInput = this.startInput ? this.startInput : this.startNowTime
      let endInput = this.endInput ? this.endInput : this.endNowTime
      let accountCategoryIds = []
      this.types.forEach((type) => {
        if (!type.active) return
        accountCategoryIds.push(type.value)
      })

      let params = {
        accountBookId: this.bookId,
        accountCategoryIds: accountCategoryIds,
        startTime: startInput,
        endTime: endInput
      }

      this.$refs['Confirm'].open({
        title: '提示',
        content: `是否确认导出 [${startInput}-${endInput}] 时间段和其他选择条件(账本、类型、类别)的账单明细记录?`,
        callback: (action) => {
          if (action == 'sumbit') {
            // 导出数据并发送邮件
            this.$u.api.exportRecordsAndSend(params).then((res) => {
              this.$u.toast('导出成功，请稍后在绑定邮箱中进行查收~')
            })
          }
        }
      })
    },
    /**
     * 折叠筐改变事件
     */
    itemChange(e) {
      // 计算高度
      if (e.show) {
        // 动态获取剩余的高度
        var that = this
        uni.getSystemInfo({
          success: function (res) {
            that._data.pH = res.windowHeight //windoHeight为窗口高度，主要使用的是这个
            let titleH = uni.createSelectorQuery().select('.sv') //想要获取高度的元素名（class/id
            titleH
              .boundingClientRect((data) => {
                let pH = that._data.pH
                let collapseHeightPx = that.$u.utils.rpxTopx(that._data.collapseHeight)
                that._data.navHeight = pH - data.top - collapseHeightPx //计算高度：元素高度=窗口高度-元素距离顶部的距离（data.top）
              })
              .exec()
          }
        })
      } else {
        // 动态获取剩余的高度
        var that = this
        uni.getSystemInfo({
          success: function (res) {
            that._data.pH = res.windowHeight //windoHeight为窗口高度，主要使用的是这个
            let titleH = uni.createSelectorQuery().select('.sv') //想要获取高度的元素名（class/id）
            titleH
              .boundingClientRect((data) => {
                let pH = that._data.pH
                let collapseHeightPx = that.$u.utils.rpxTopx(that._data.collapseHeight)
                that._data.navHeight = pH - data.top + collapseHeightPx - 30 //计算高度：元素高度=窗口高度-元素距离顶部的距离（data.top）
              })
              .exec()
          }
        })
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.slot-content {
  background-color: #ffffff;
  padding: 10rpx 24rpx;

  .type-y-btn {
    border: 1px solid $u-type-primary;
    background-color: $u-type-primary;
    color: #ffffff;
    padding: 0% 10%;
    border-radius: 10rpx;
    font-size: 30rpx;
  }

  .type-n-btn {
    border: 1px solid $u-type-error;
    background-color: $u-type-error;
    color: #ffffff;
    padding: 0% 10%;
    border-radius: 10rpx;
    font-size: 30rpx;
  }

  .item-box {
    margin-bottom: 50rpx;
    display: flex;
    flex-wrap: wrap;
    // justify-content: space-between;

    .item {
      border: 1px solid $u-type-success;
      color: $u-type-success;
      padding: 8rpx 40rpx;
      margin: 0 10rpx;
      border-radius: 100rpx;
      margin-top: 20rpx;
    }

    .active {
      color: #ffffff;
      background-color: $u-type-success;
    }
  }
}

.top {
  margin: 20rpx 40rpx;
  font-size: 25rpx;

  .color-blue {
    color: $u-type-primary;
    margin-right: auto;
    justify-content: flex-start;
  }

  .color-green {
    color: $u-type-success;
    justify-content: center;
  }

  .color-red {
    color: $u-type-error;
    margin-left: auto;
    justify-content: flex-end;
  }
}

.picker-border {
  background-color: #ffffff;
  margin: 0 auto;
  border-radius: 20rpx;
  box-sizing: border-box;
  padding: 20rpx;
  font-size: 28rpx;
}

.chartsMain {
  width: 750rpx;
  height: 550rpx;
  padding-top: 25rpx;
  background: #fff;
  margin-bottom: 24rpx;
  border-top: 2rpx solid #f2f2f2;
  .charts {
    width: 750rpx;
    height: 550rpx;
    box-sizing: border-box;
  }
}

.order {
  width: 710rpx;
  background-color: #ffffff;
  margin: 0 20rpx 0 20rpx;
  border-radius: 20rpx;
  box-sizing: border-box;
  padding: 10rpx;
  font-size: 28rpx;
	display: flex;

  .order-item {
    display: flex;
    justify-content: space-between;

    .left {
      margin: 20rpx 0 20rpx 20rpx;

      .title {
        font-size: 35rpx;
        line-height: 45rpx;
      }
    }

    .right {
      margin: 20rpx 20rpx 20rpx 360rpx;

      .expenditure-type {
        color: $u-type-error;
        font-size: 35rpx;
        line-height: 45rpx;
      }

      .income-type {
        color: $u-type-success;
        font-size: 35rpx;
        line-height: 45rpx;
      }
    }
  }
}

.swipe-right-item-blue {
  margin: 20rpx auto;
  border-radius: 20rpx;
  box-sizing: border-box;
  padding: 20rpx;

  display: flex;
  flex-direction: row;
  justify-content: center;
  align-items: center;

  width: 150rpx;
  background-color: #007aff;
  color: #ffffff;
  padding: 20rpx;
  font-size: 35rpx;
}
</style>
